package service;


import dao.UserMessageTD;

import jakarta.websocket.Session;
import lombok.extern.log4j.Log4j2;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import pojo.message.imp.ChatMessage;
import pojo.message.imp.Message;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Log4j2
@Service
public class SubmitMessage {
    private static UserMessageTD userMessageTD;
    @Autowired
    public SubmitMessage(UserMessageTD userMessageTD) {
        this.userMessageTD = userMessageTD;
    }
    public  static boolean submitMessage(String id_from,String id_to,Session session_to,String message){
        log.info(id_from+" "+id_to);
        System.out.println(id_from+" "+id_to);
        try{
            if(session_to!=null){//如果好友在线
                session_to.getAsyncRemote().sendText(message);
            }else{
                saveMessageToDateBase(id_from,id_to,message);
            }
        }catch (Exception e){
            log.error("submitMessage 发生了错误 "+e);
            return false;
        }
        return true;
    }
    public static List<ChatMessage> getMessage(String id){
        List<String> friendsMessageListByFriendId;
        List<ChatMessage> result=new LinkedList<>();
        List<Message> message;
        if(userMessageTD.getMessageCount(id)>0){
            friendsMessageListByFriendId=userMessageTD.getFriendsList(id);
            for(String id_friend:friendsMessageListByFriendId){
                //取信息
                message=userMessageTD.getMessageForId(id_friend,id);//从朋友到我自己的信息
                ChatMessage chatMessage=new ChatMessage();
                chatMessage.setMessages(message);
                chatMessage.setId_from(id_friend);
                chatMessage.setId_to(id);
                //更新信息
//                userMessageTD.updateMessageCount()
            }
        }
        return result;
    }
    public static List<Message> getMessageForId(String myId,String friendId){
        List<Message> list=userMessageTD.getMessageForId(friendId,myId);
        userMessageTD.deleteMessageForId(friendId,myId);
        userMessageTD.updateMessageCount(myId,-list.size());
        userMessageTD.updateMessageCounttoFriend(friendId,myId,-list.size());
        return list;
    }
    private static boolean saveMessageToDateBase(String id_from,String id_to,String message){
        Date date=new Date(System.currentTimeMillis());
        userMessageTD.insertMessage(id_from,id_to,date,message);//记录信息A 发送给 B 信息
        userMessageTD.updateMessageCounttoFriend(id_to,id_from,1);//给朋友的信息数量更新
        userMessageTD.updateMessageCount(id_to,1);//给朋友更新信息数量
        return true;
    }


}
